package com.workcell.workdata.xthings.dao.impl;

import cn.hutool.core.util.StrUtil;
import com.workcell.workdata.xthings.dao.PartitionDao;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class PartitionDaoImpl implements PartitionDao {
    private final JdbcTemplate jdbcTemplate;

    /**
     * 查询分区数量
     *
     * @param tableName 表名
     * @param partitionName 分区名
     * @return 分区数量
     */
    @Override
    public Long count(String tableName, String partitionName) {
        String sql = "select count(*) from information_schema.PARTITIONS " +
                "where TABLE_NAME = ? " +
                "and PARTITION_NAME = ?";

        return jdbcTemplate.queryForObject(sql, new SingleColumnRowMapper<>(), tableName, partitionName);
    }

    /**
     * 创建分区
     *
     * @param tableName 表名
     * @param partitionName 分区名
     * @param level 级别
     */
    @Override
    public void createPartition(String tableName, String partitionName, String level) {
        String sqlPattern = "alter table {} " +
                "    add partition ( " +
                "            partition {} values less than (to_days(?))" +
                "        )";

        String sql = StrUtil.format(sqlPattern, tableName, partitionName);
        jdbcTemplate.update(sql, level);
    }
}
